import 'dart:developer';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/king/king_detail_logic.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/toast_utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:sports_new/widgets/base/qkd_dialog.dart';
import '../../resources/colours.dart';
import '../../utils/utils.dart';
import '../../widgets/base/qkd_text.dart';

class KingDetailPage extends StatefulWidget {
  const KingDetailPage({super.key});

  @override
  State<KingDetailPage> createState() => _KingDetailPageState();
}

class _KingDetailPageState extends State<KingDetailPage> {
  final KingDetailLogic logic = Get.put(KingDetailLogic());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<KingDetailLogic>(
      builder: (logic) {
        return WillPopScope(
          onWillPop: () async{
            Get.back(result: logic.hasCommit);
            return true;
          },
          child: Scaffold(
            appBar: Styles.appBar(
              title: QkdText(logic.data?.item.hasValue == true?"我的预测":"选择预测结果"),
              onTapLeading: () => Get.back(result: logic.hasCommit)
            ),
            body: Container(
              height: Get.height,
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Column(
                children: [
                  matchLabel().paddingOnly(top: 12),
                  title("本场胜平负结果").paddingOnly(top: 20),
                  Row(
                    children: List<Widget>.generate(3, (index) =>
                      Expanded(
                        child: chooseItem(
                          logic.betWin[index],
                          logic.data?.spfOdds?[index] ?? "",
                          logic.winIndex.contains(index)
                        ).tap(() {
                          if(logic.data?.status != 1) return;
                          if(logic.winIndex.length == 2
                            && !logic.winIndex.contains(index)) {
                            ToastUtils.showDismiss("每个玩法最多选择两项");
                          }else{
                            logic.setWinIndex(
                              index,logic.winIndex.contains(index));
                          }
                        }),
                      )
                    ).insertWith(0, [chooseItem(logic.handicap, "",false,width: 40)]
                    ).insertEvery(Container(width: 8))
                  ).paddingOnly(top: 10),
                  title("本场双方进球数之和").paddingOnly(top: 20),
                  SizedBox(
                    width: Get.width,
                    child: Wrap(
                      runSpacing: 10,
                      alignment: WrapAlignment.spaceBetween,
                      children: List.generate(
                        logic.betPoints.length, (index) =>
                        chooseItem(
                          logic.betPoints[index],
                          logic.data?.jqsOdds?[index] ?? "",
                          logic.pointsIndex.contains(index),
                          width: (Get.width-32-7)/2
                        ).tap(() {
                          if(logic.data?.status != 1) return;
                          if(logic.pointsIndex.length == 2
                            && !logic.pointsIndex.contains(index)) {
                            ToastUtils.showDismiss("每个玩法最多选择两项");
                          }else{
                            logic.setPointsIndex(
                              index,logic.pointsIndex.contains(index));
                          }
                        })
                      )
                    ).paddingOnly(top: 10),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      QkdText("免费次数：${logic.data?.sendCount}次",
                        fontSize: 12,color: Colours.grey66
                      ),
                      Container(width: 4),
                      Image.asset(
                          width: 12,
                          Utils.getImgPath("question_mark_border.png")
                      ).tap(() => Get.dialog(QkdDialog.single(
                          "免费次数说明",content:
                      "1.每场比赛会赠送您2次预测机会。\n"
                          "2.赠送次数在最后一场比赛预测截止时失效。\n"
                          "3.比赛取消不退还赠送次数。"))),
                      Container(width: 16),
                      QkdText("赠送次数：${logic.data?.saveCount ?? ""}次",
                          fontSize: 12,color: Colours.grey66),
                      Container(width: 4),
                      Image.asset(
                          width: 12,
                          Utils.getImgPath("question_mark_border.png")
                      ).tap(() => Get.dialog(QkdDialog.single(
                          "赠送次数说明",content:
                      "1.每充值50元自动兑换1次预测机会。\n"
                          "2.充值兑换次数有效期3个月。\n"
                          "3.比赛取消退还兑换次数。")))
                    ]
                  ).paddingOnly(top: 20),
                  const Spacer(),
                  if(logic.data?.status == 1 && logic.data?.item.noValue == true)
                  Row(
                    children: [
                      QkdButton(
                        width: (Get.width-40-16)/2,
                        height: 44,
                        text: "清空",
                        borderRadius: 8,
                        backgroundColor: Colours.greyF2,
                        textStyle: const TextStyle(fontSize: 16,color: Colours.grey66),
                        onPressed: (){
                          logic.pointsIndex = [];
                          logic.winIndex = [];
                          update();
                      }),
                      const Spacer(),
                      QkdButton(
                        width: (Get.width-40-16)/2,
                        height: 44,
                        text: "确定",
                        borderRadius: 8,
                        backgroundColor: Colours.main,
                        textStyle: const TextStyle(fontSize: 16,color: Colours.white),
                        onPressed: () async{
                          if(logic.winIndex.length+logic.pointsIndex.length == 0) {
                            return ToastUtils.showDismiss("您尚未进行选择");
                          }
                          var result = await Get.dialog(
                            QkdDialog.alert("您预测本场比赛",
                              contentWidget: Column(
                                children: [
                                  if(logic.winIndex.isNotEmpty)...[
                                    QkdText("主队加${logic.handicap}球后：${
                                      List.generate(logic.winIndex.length,
                                      (index) {
                                        return logic.betWin[logic.winIndex[index]];
                                      }).join("、")}"
                                    ),
                                    Container(height: 6)
                                  ],
                                  if(logic.pointsIndex.isNotEmpty)
                                  QkdText("双方进球之和：${
                                    List.generate(logic.pointsIndex.length,
                                    (index) {
                                      return logic.betPoints[logic.pointsIndex[index]];
                                    }).join("、")}"
                                  )
                                ],
                              )
                            )
                          );
                          if(result) logic.commit();
                        })
                    ],
                  ).paddingSymmetric(horizontal: 4),
                  Container(height: MediaQuery.of(context).padding.bottom+10)
                ],
              ),
            )
          ),
        );
      }
    );
  }
  
  Widget chooseItem(String text,String odds,bool choose,{double? width}){
    return Stack(
      alignment: Alignment.centerRight,
      children: [
        Container(
          width: width,
          height: 41,
          alignment: Alignment.center,
          clipBehavior: Clip.antiAlias,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            border: choose?null:Border.all(color: Colours.greyDD,width: 0.5),
            color: choose?
              logic.data?.item.noValue == true?
                Colours.main:Colours.redBC4F4F
              :Colours.greyF2F3F7),
          child: Column(
            mainAxisAlignment: odds.hasValue?MainAxisAlignment.spaceBetween:MainAxisAlignment.center,
            children: [
              Container(height: 4),
              QkdText(text,
                  color: choose?Colours.white:Colours.grey66
              ),
              if(odds.hasValue)
              QkdText(odds,
                fontSize: 11,
                color: choose?Colours.white:Colours.grey66
              ),
              Container(height: 3)
            ],
          )
        ),
        if(logic.result.contains(text))
        Positioned(
          right: 14,
          child: Image.asset(width: 12,Utils.getImgPath("king_result_${choose?"aim":"miss"}.png")))
      ],
    );
  }

  Widget title(String name){
    return Row(
        children: [
          QkdText(name, fontSize: 15),
          Container(width: 4),
          Image.asset(
            width: 14,Utils.getImgPath("question_mark_border.png")
          ).tap(() {
            if(name == "本场胜平负结果") {
              Get.dialog(QkdDialog.single("胜平负结果说明",
                content: "1、若球线为0时，则最终结果以比赛胜平负结果判定胜平负\n"
                  "2、若球线不为0时，则最终结果以主队进球数减去球线后的结果判定胜平负\n"
                  "3、均已90分钟（含伤停补时）进球数为准")
              );
            }
            if(name == "本场双方进球数之和"){
              Get.dialog(QkdDialog.single("总进球结果说明",
                content: "1、即比赛结束后，主客队进球数之和\n"
                  "2、若和大于7，则正确选项为7球及以上\n"
                  "3、均已90分钟（含伤停补时）进球数为准")
              );
            }
          }),
          Container(width: 4),
          QkdText("(猜中获得赔率*10积分)",
            fontSize: 12,color: Colours.grey99)
        ]
    );
  }

  Widget matchLabel(){
    return Container(
      clipBehavior: Clip.antiAlias,
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
          border: Border.all(color: Colours.main,width: 1),
          borderRadius: BorderRadius.circular(10),
          color: Colours.greyF5F7FA
      ),
      child: Column(
        children: [
          QkdText("${logic.data?.leagueName ?? ""} ${logic.data?.matchTime ?? ""}",
              fontSize: 12,color: Colours.grey66),
          Divider(
              color: Colours.main.withOpacity(0.2),height: 0.5
          ).paddingSymmetric(horizontal: 6,vertical: 10),
          Row(
            children: [
              Expanded(
                child: Column(
                  children: [
                    CachedNetworkImage(
                        width: 52,
                        height: 52,
                        placeholder: (context, url) => Styles.placeholderIcon(),
                        errorWidget: (context, url, error,) =>
                            Image.asset(Utils.getImgPath("zq_placeholder.png")),
                        imageUrl: logic.data?.homeLogo ?? ""),
                    Container(height: 4),
                    QkdText(logic.data?.homeName ?? "",
                        textAlign: TextAlign.center,
                        fontWeight: FontWeight.w500
                    )
                  ],
                ),
              ),
              QkdText.style(logic.data?.guessTime ?? "",
                style: logic.data?.guessTime?.contains(":") == true?
                const TextStyle(
                  color: Colours.text, fontSize: 22,
                  fontWeight: FontWeight.w500,fontFamily: "Din"):
                const TextStyle(fontSize: 14,color: Colours.grey66),
                textAlign: TextAlign.center),
              Expanded(
                child: Column(
                  children: [
                    CachedNetworkImage(
                      width: 52,
                      height: 52,
                      placeholder: (context, url) => Styles.placeholderIcon(),
                      errorWidget: (context, url, error,) =>
                        Image.asset(Utils.getImgPath("zq_placeholder.png")),
                      imageUrl: logic.data?.guestLogo ?? ""),
                    Container(height: 4),
                    QkdText(logic.data?.guestName ?? "",
                      textAlign: TextAlign.center,
                      fontWeight: FontWeight.w500)
                  ],
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}
